/**
 * 设备控制器模块
 * controller\device.js
 *
 * 说明：
 * 中间件处理路由请求：
 * 1. req.params --> 路由参数 /:id  -> req.params.id
 * 2. req.query  --> url查询串  ?k1=v1&k2=v2  -> req.query.k1, req.query.k2
 * 3. req.body   --> 数据对象  {k1:v1, k2:v2} -> req.body.k1, req.body.k2
 *
 * 中间件进行异步封装（async/await），不会直接执行，需要进行函数立即执行的方式。
 */
 
const express = require("express");
 
const util = require("../common/util");
/**
 * @typedef {DeviceDB}
 */
const DeviceDB = require("../model/sqlite/labs");
 
/**
 * 获取设备信息
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function find(req, res) {
  (async function () {
    let db = DeviceDB.getInstance();
    await db.connect();
    let result = await db.find(req.params.id);
    //await db.close();
    util.logFormat(`获取【${req.params.id}】设备信息%O`, result);
    res.json(
      util.FormatJSONData(200, `获取设备信息【${req.params.id}】`, result)
    );
  })();
}
 
/**
 * 获取设备信息列表
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function findAll(req, res) {
  (async function () {
    //1.处理输入的数据
    //FIXME: 输入数据的正确性校验，一致性校验，完整性校验
    let limit = req.query.limit ? req.query.limit : -1;
    let offset = req.query.offset ? req.query.offset : -1;
    //2. 访问数据
    let db = DeviceDB.getInstance();
    await db.connect();
    let result = await db.findAll(limit, offset);
    //await db.close();
 
    //3.输出数据
    util.logFormat(`获取【limit=${limit}&offset=${offset}】设备信息%O`, result);
    res.json(util.FormatJSONData(200, `获取设备信息列表`, result));
  })();
}
 
/**
 * 新增设备信息
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function add(req, res) {
  (async function () {
    //FIXME:req.body的数据安全性校验
    let device = {
        title:req.body.title,
        imageurl:req.body.imageurl, //FIXME:处理远程图片为本地图片
        spcialtype:req.body.spcialtype,
        status:req.body.status,
        category:req.body.category,
        identify:req.body.identify,
        price:req.body.price,
        danwei:req.body.danwei,
        contact:req.body.contact,
        phone:req.body.phone,
        email:req.body.email,
        location:req.body.location,
        xiamenId:req.body.xiamenId,
        technicalSpecs:req.body.technicalSpecs, 
        mainFunctions:req.body.mainFunctions,
        serviceContent:req.body.serviceContent, 
        openSharingRules:req.body.openSharingRules,
        createdTime:Date.now(),
        updatedTime:Date.now(),     
    };
    let db = DeviceDB.getInstance();
    await db.connect();
    //FIXME:插入数据前、考虑校验是否存在xiamenId
    let result = await db.add(device);
    //await db.close();
    util.log(`新增设备信息：lastID->${result}`);
    res.json(util.FormatJSONData(201, `新增设备信息`, { lastID: result }));
  })();
}
 
/**
 * 更新设备信息
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function update(req, res) {
  (async function () {
    //FIXME:req.body的数据安全性校验
    let device = {
        id:req.params.id,
        title:req.body.title,
        imageurl:req.body.imageurl, //FIXME:处理远程图片为本地图片
        spcialtype:req.body.spcialtype,
        status:req.body.status,
        category:req.body.category,
        identify:req.body.identify,
        price:req.body.price,
        danwei:req.body.danwei,
        contact:req.body.contact,
        phone:req.body.phone,
        email:req.body.email,
        location:req.body.location,
        xiamenId:req.body.xiamenId,
        technicalSpecs:req.body.technicalSpecs, 
        mainFunctions:req.body.mainFunctions,
        serviceContent:req.body.serviceContent, 
        openSharingRules:req.body.openSharingRules,
        updatedTime:Date.now(),     
    };
 
    let db = DeviceDB.getInstance();
    await db.connect();
    let result = await db.update(device);
    //await db.close();
    util.log(`更新设备信息：changes->${result}`);
    res.json(util.FormatJSONData(200, `更新设备信息`, { changes: result }));
  })();
}
 
/**
 * 删除设备信息
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function remove(req, res) {
  (async function () {
    //FIXME:数据合法性校验
    let deviceId = req.params.id;
    let db = DeviceDB.getInstance();
    await db.connect();
    let result = await db.remove(deviceId);
    //await db.close();
    util.log(`删除设备信息：changes->${result}`);
    res.json(util.FormatJSONData(204, `删除设备信息`, { changes: result }));
  })();
}
/**
 * 获取设备总数
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function getCount(req, res) {
    (async function () {
        //FIXME:数据合法性校验
        let db = DeviceDB.getInstance();
        await db.connect();
        let result = await db.getCount();
        //await db.close();
        util.log(`设备总数：${result}`);
        res.json(util.FormatJSONData(200, `获取设备总数`, result));
    })();
}


/**
 * 获取设备信息列表
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
function search(req, res) {
  (async function () {
    //1.处理输入的数据
    //FIXME: 输入数据的正确性校验，一致性校验，完整性校验
    let q=req.query.q;
    let limit = req.query.limit ? req.query.limit : -1;
    let offset = req.query.offset ? req.query.offset : -1;
    //2. 访问数据
    let db = DeviceDB.getInstance();
    await db.connect();
    let result = await db.search(q,limit, offset);
    //await db.close();
 
    //3.输出数据
    util.logFormat(`获取关键字为【${q}】【limit=${limit}&offset=${offset}】设备信息%O`, result);
    res.json(util.FormatJSONData(200, `获取指定关键字的设备信息列表`, result));
  })();
}
 

	/**
 * 获取指定ID号的设备信息
 * @param {express.Request} req  请求
 * @param {express.Response} res  响应
 */
  function findById(req, res) {
    //FIXME: ID号的合法性校验
    (async function () {
      let db = DeviceDB.getInstance();
      await db.connect();
      let result = await db.findByID(req.params.id);
      //await db.close();
      util.logFormat(`获取【${req.params.id}】设备信息%O`, result);
      res.json(
        util.FormatJSONData(200, `获取指定ID的设备信息`, result)
      );
    })();
  }

module.exports = {
  find,
  findAll,
  add,
  update,
  remove,
  getCount,
  search,
  findById
};
 
